// releasePage/pages/addOperator/addOperator.js
import throttle from '../../../utils/throttle.js';
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        review: '', //审核编辑标记位
        // 运营商id
        id: '',
        fromWhere: '', //01--从城市运营商编辑
        // logo
        src: '',
        // 运营商名称
        operatorName: '',
        // 国家或地区
        countryOrArea: '',
        // 地区首字母
        pinyinsimple: '',
        // 地区全拼音
        pinyindetail: '',
        // 补充说明内容
        textareaValue: '',
        networkSupportArr: [
            {
                name: 'NR',
                value: '00',
                checked: false,
            },
            {
                name: 'VoLTE',
                value: '06',
                checked: false,
            },
            {
                name: 'ViLTE',
                value: '03',
                checked: false,
            },
            {
                name: 'VoWiFi',
                value: '02',
                checked: false,
            },
            {
                name: 'ViWiFi',
                value: '01',
                checked: false,
            },
            {
                name: 'TD-LTE',
                value: '04',
                checked: false,
            },
            {
                name: 'FDD-LTE',
                value: '05',
                checked: false,
            },
        ],
        checkRadio3g: [
            {
                name: 'WCDMA',
                value: '07',
                checked: false,
            },
            {
                name: 'CDMA2000',
                value: '08',
                checked: false,
            },
            {
                name: 'TD-SCDMA',
                value: '09',
                checked: false,
            },
        ],
        checkRadio2g: [
            {
                name: 'GSM',
                value: '10',
                checked: false,
            },
            {
                name: 'CDMA1x',
                value: '11',
                checked: false,
            },
        ],
        checkRadio3gValue: '',
        checkRadio2gValue: '',
        // 传递给后台的网络支持,逗号拼接的字符串
        networkSupport: '',
        // apn接入点数组
        apnArr: [
            {
                name: '',
                sceneImageArr: [],
            },
        ],
        // apn是否都有数据
        isApnComplete: false,
        // ussd数组
        ussdArr: [
            {
                name: '话费充值',
                value: '',
            },
            {
                name: '号码查询',
                value: '',
            },
            {
                name: '话费余额',
                value: '',
            },
            {
                name: '数据余额',
                value: '',
            },
            {
                name: '语音套餐充值',
                value: '',
            },
            {
                name: '数据套餐充值',
                value: '',
            },
            {
                name: '语音套餐余额',
                value: '',
            },
            {
                name: '数据套餐余额',
                value: '',
            },
        ],
        //LTE网络设备商
        lteNetwork: false,
        lteNetworkRange: '', //区域划分界限
        ltebasestation: '', //基站信息
        ltebasestationid: '',
        ltecorenet: '', //核心网信息
        ltecorenetid: '',
        lteipmedia: '', //ip多媒体系统
        lteipmediaid: '',
        ltechannelsupport: '', //频段支持
        ltechannelsupportid: '',
        //NR网络设备商
        nrNetwork: false,
        nrNetworkRange: '', //区域划分界限
        nrbasestation: '', //基站信息
        nrbasestationid: '',
        nrcorenet: '', //核心网信息
        nrcorenetid: '',
        nrchannelsupport: '', //频段支持
        nrchannelsupportid: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.id) {
            this.setData(
                {
                    id: options.id,
                    review: options.review || '',
                },
                () => {
                    this.getCityOperatorDetail();
                }
            );
            wx.setNavigationBarTitle({
                title: '编辑运营商',
            });
        } else {
            wx.setNavigationBarTitle({
                title: '添加运营商',
            });
        }
        if (options.fromWhere == '01') {
            //从城市主页页面跳转、显示设备商
            this.setData({
                lteNetwork: true,
                nrNetwork: true,
                fromWhere: options.fromWhere,
            });
        }
    },

    // 网络支持checkbox
    checkboxChange(e) {
        console.log(e.detail.value);
        this.setData({
            networkSupport: e.detail.value.join(','),
        });
    },
    // 网络支持单选
    checkRadio3g: function (e) {
        let items = this.data.checkRadio3g;
        for (let i = 0; i < items.length; i++) {
            if (items[i].value == this.data.checkRadio3gValue) {
                for (let j = 0; j < items.length; j++) {
                    if (items[j].checked && j != i) {
                        items[j].checked = false;
                    }
                }
                items[i].checked = !items[i].checked;
            }
        }
        this.setData({
            checkRadio3g: items,
        });
    },
    radioChange3: function (e) {
        this.setData({
            checkRadio3gValue: e.detail.value,
        });
    },
    checkRadio2g: function (e) {
        let items = this.data.checkRadio2g;
        for (let i = 0; i < items.length; i++) {
            if (items[i].value == this.data.checkRadio2gValue) {
                for (let j = 0; j < items.length; j++) {
                    if (items[j].checked && j != i) {
                        items[j].checked = false;
                    }
                }
                items[i].checked = !items[i].checked;
            }
        }
        this.setData({
            checkRadio2g: items,
        });
    },
    radioChange2: function (e) {
        this.setData({
            checkRadio2gValue: e.detail.value,
        });
    },
    onInput: throttle(
        function (e) {
            let item = e.currentTarget.dataset.item;
            this.setData(
                {
                    [item]: e.detail.value,
                },
                () => {
                    if (item.indexOf('apn') > -1) {
                        this.isApnComplete();
                    }
                }
            );
        },
        200,
        {
            trailing: false,
        }
    ),
    //打开网络设备商
    openNetwork(e) {
        if (e.currentTarget.dataset.index == 1) {
            this.setData({
                nrNetwork: !this.data.nrNetwork, //NR网络设备商
            });
        } else {
            this.setData({
                lteNetwork: !this.data.lteNetwork, //LTE网络设备商
            });
        }
    },
    // 添加图片
    addImg(e) {
        let apnIndex = e.currentTarget.dataset.apnindex;
        const that = this;
        wx.chooseImage({
            count: 9 - that.data.apnArr[apnIndex].sceneImageArr.length,
            success(res) {
                let imgLen =
                    that.data.apnArr[apnIndex].sceneImageArr.length +
                    res.tempFilePaths.length;
                if (imgLen > 9) {
                    wx.showModal({
                        content: '最多上传8张图片，请重新上传',
                        showCancel: false,
                    });
                    return;
                } else {
                    wx.showLoading({
                        title: '图片上传中',
                        mask: true,
                    });
                    const imgUploadResults = [];
                    let index = that.data.apnArr[apnIndex].sceneImageArr.length;
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        let imgUploadResult = app
                            .imgUpload(res.tempFilePaths[i])
                            .then((res) => {
                                let num = i + index;
                                that.data.apnArr[apnIndex].sceneImageArr[
                                    num
                                ] = res;
                                let arr =
                                    'apnArr[' + apnIndex + '].sceneImageArr';
                                that.setData({
                                    [arr]:
                                        that.data.apnArr[apnIndex]
                                            .sceneImageArr,
                                });
                                console.log(
                                    that.data.apnArr[apnIndex].sceneImageArr
                                );
                                // 判断是否完填写apn
                                that.isApnComplete();
                            });
                        imgUploadResults.push(imgUploadResult);
                    }
                    Promise.all(imgUploadResults).then((values) => {
                        wx.hideLoading();
                    });
                }
            },
        });
    },
    // 判断是否完填写apn
    isApnComplete() {
        let isApnComplete = this.data.apnArr.every((item) => {
            return item.name;
        });
        this.setData({
            isApnComplete,
        });
    },
    // 删除图片
    deleteImg(e) {
        let index = e.currentTarget.dataset.index;
        let apnIndex = e.currentTarget.dataset.apnindex;
        console.log(index);
        this.data.apnArr[apnIndex].sceneImageArr.splice(index, 1);

        // 判断是否完填写apn
        this.isApnComplete();

        this.setData({
            apnArr: this.data.apnArr,
        });
    },

    // 预览图片
    previewImage(e) {
        const current = e.currentTarget.dataset.src;
        let apnIndex = e.currentTarget.dataset.apnindex;
        if (typeof apnIndex === 'number') {
            wx.previewImage({
                current,
                urls: this.data.apnArr[apnIndex].sceneImageArr,
            });
        } else {
            wx.previewImage({
                current,
                urls: [current],
            });
        }
    },

    // 添加apn
    addApn() {
        this.data.apnArr.push({
            name: '',
            sceneImageArr: [],
        });
        this.setData({
            apnArr: this.data.apnArr,
        });
        this.isApnComplete();
    },

    // 删除apn
    deleteApn(e) {
        let apnIndex = e.currentTarget.dataset.apnindex;
        this.data.apnArr.splice(apnIndex, 1);
        this.setData({
            apnArr: this.data.apnArr,
        });
        this.isApnComplete();
    },

    upload() {
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
            success(res) {
                const src = res.tempFilePaths[0];
                wx.navigateTo({
                    url: `../cropper/cropper?src=${src}`,
                });
            },
        });
    },

    bindKeyInput(e) {
        this.setData({
            operatorName: e.detail.value,
        });
    },

    changeNav: throttle(
        (e) => {
            let nav = e.currentTarget.dataset.nav;
            console.log(nav);
            wx.navigateTo({
                url: nav,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    submit: throttle(
        function () {
            if (app.visitorPublish()) return; //游客发布限制
            if (
                !(
                    this.data.src &&
                    this.data.operatorName &&
                    this.data.countryOrArea &&
                    this.data.networkSupport &&
                    this.data.isApnComplete
                )
            )
                return;
            let _that = this;
            let postData = {};
            let networkSupportValue = _that.data.networkSupport;
            for (let i = 0; i < _that.data.checkRadio3g.length; i++) {
                if (_that.data.checkRadio3g[i].checked) {
                    console.log(networkSupportValue);
                    if (networkSupportValue.includes('07')) {
                        networkSupportValue = networkSupportValue.replace(
                            '07',
                            _that.data.checkRadio3g[i].value
                        );
                        console.log(networkSupportValue);
                    } else if (networkSupportValue.includes('08')) {
                        networkSupportValue = networkSupportValue.replace(
                            '08',
                            _that.data.checkRadio3g[i].value
                        );
                        console.log(networkSupportValue);
                    } else if (networkSupportValue.includes('09')) {
                        networkSupportValue = networkSupportValue.replace(
                            '09',
                            _that.data.checkRadio3g[i].value
                        );
                        console.log(networkSupportValue);
                    } else {
                        networkSupportValue =
                            networkSupportValue +
                            ',' +
                            _that.data.checkRadio3g[i].value;
                        console.log(networkSupportValue);
                    }
                }
            }
            for (let i = 0; i < _that.data.checkRadio2g.length; i++) {
                if (_that.data.checkRadio2g[i].checked) {
                    if (networkSupportValue.includes('10')) {
                        networkSupportValue = networkSupportValue.replace(
                            '10',
                            _that.data.checkRadio2g[i].value
                        );
                        console.log(networkSupportValue);
                    } else if (networkSupportValue.includes('11')) {
                        console.log(networkSupportValue);
                        networkSupportValue = networkSupportValue.replace(
                            '11',
                            _that.data.checkRadio2g[i].value
                        );
                    } else {
                        networkSupportValue =
                            networkSupportValue +
                            ',' +
                            _that.data.checkRadio2g[i].value;
                        console.log(networkSupportValue);
                    }
                }
            }
            postData.country = _that.data.countryOrArea;
            postData.operator = _that.data.operatorName;
            postData.operatorpicurl = _that.data.src;
            postData.networksupport = networkSupportValue;
            postData.apnpoint = JSON.stringify(_that.data.apnArr);
            postData.apnpointcount = _that.data.apnArr.length;
            postData.ussd = JSON.stringify(_that.data.ussdArr);
            postData.backup = _that.data.textareaValue;
            postData.pinyinsimple = _that.data.pinyinsimple;
            postData.pinyindetail = _that.data.pinyindetail;

            wx.showModal({
                title: '确认提交？',
                content: '',
                success: function (res) {
                    if (res.confirm) {
                        if (_that.data.id) {
                            postData.id = _that.data.id;
                            postData.nr = {
                                //NR网络设备商
                                basestation:
                                    _that.data.nrbasestationid || undefined,
                                corenet: _that.data.nrcorenetid || undefined,
                                channelsupport:
                                    _that.data.nrchannelsupportid || undefined,
                                regionlimit:
                                    _that.data.nrNetworkRange || undefined, //区域划分界限
                            };
                            postData.nr =
                                JSON.stringify(postData.nr) == '{}'
                                    ? undefined
                                    : postData.nr;
                            postData.lte = {
                                basestation:
                                    _that.data.ltebasestationid || undefined,
                                corenet: _that.data.ltecorenetid || undefined,
                                ipmedia: _that.data.lteipmediaid || undefined,
                                channelsupport:
                                    _that.data.ltechannelsupportid || undefined,
                                regionlimit:
                                    _that.data.lteNetworkRange || undefined, //区域划分界限
                            };
                            postData.lte =
                                JSON.stringify(postData.lte) == '{}'
                                    ? undefined
                                    : postData.lte;
                            wx.request({
                                method: 'POST',
                                url:
                                    app.globalData.rootPath +
                                    'cjMap/editCityOperator?authId=' +
                                    app.globalData.authId +
                                    '&city=' +
                                    app.globalData.addressBack +
                                    '&country=' +
                                    app.globalData.countryBack,
                                data: postData,
                                success(res) {
                                    if (res.data.status === '0') {
                                        if (!_that.data.review) {
                                            let pages = getCurrentPages(); //当前页面栈

                                            let prevPage =
                                                pages[pages.length - 2];
                                            if (
                                                prevPage &&
                                                typeof prevPage.refresh ==
                                                    'function'
                                            ) {
                                                prevPage.refresh(['operator']);
                                            }

                                            let prevPage2 =
                                                pages[pages.length - 3];
                                            if (
                                                prevPage2 &&
                                                typeof prevPage2.refresh ==
                                                    'function'
                                            ) {
                                                prevPage2.refresh();
                                            }

                                            let prevPage3 =
                                                pages[pages.length - 4];
                                            if (
                                                prevPage3 &&
                                                typeof prevPage3.refresh ==
                                                    'function'
                                            ) {
                                                prevPage3.refresh();
                                            }

                                            wx.showToast({
                                                title: '提交成功',
                                                icon: 'success',
                                                duration: 1500,
                                            });
                                            setTimeout(function () {
                                                wx.navigateBack({
                                                    delta: 1,
                                                });
                                            }, 2000);
                                        } else {
                                            app.doVerify(
                                                res.data.data.id,
                                                '17'
                                            );
                                        }
                                    } else {
                                        console.log('提交失败');
                                    }
                                },
                            });
                        } else {
                            wx.request({
                                method: 'POST',
                                url:
                                    app.globalData.rootPath +
                                    'cjMap/createCityOperator?authId=' +
                                    app.globalData.authId,
                                data: postData,
                                success(res) {
                                    if (res.data.status === '0') {
                                        let pages = getCurrentPages(); //当前页面栈
                                        let prevPage = pages[pages.length - 2];
                                        if (
                                            prevPage &&
                                            typeof prevPage.refresh ==
                                                'function'
                                        ) {
                                            prevPage.refresh();
                                        }
                                        let prevPage2 = pages[pages.length - 3];
                                        if (
                                            prevPage2 &&
                                            typeof prevPage2.refresh ==
                                                'function'
                                        ) {
                                            prevPage2.refresh();
                                        }
                                        let prevPage3 = pages[pages.length - 4];
                                        if (
                                            prevPage3 &&
                                            typeof prevPage3.refresh ==
                                                'function'
                                        ) {
                                            prevPage3.refresh();
                                        }

                                        wx.showToast({
                                            title: '提交成功',
                                            icon: 'success',
                                            duration: 1500,
                                        });
                                        setTimeout(function () {
                                            wx.navigateBack({
                                                delta: 1,
                                            });
                                        }, 2000);
                                    } else {
                                        console.log('提交失败');
                                    }
                                },
                            });
                        }
                    }
                },
            });
        },
        4000,
        {
            trailing: false,
        }
    ),

    // 获取运营商详情
    getCityOperatorDetail() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/getCityOperatorDetail',
            data: {
                authId: app.globalData.authId,
                id: _that.data.id,
                city: app.globalData.addressBack,
                country: app.globalData.countryBack,
            },
            success(res) {
                if (res.data.status === '0') {
                    let temp = res.data.cityOperator.networksupport.split(',');
                    let checkRadioValue2 = '';
                    let checkRadioValue3 = '';
                    _that.data.networkSupportArr.map((item) => {
                        if (temp.includes(item.value)) {
                            item.checked = true;
                        }
                    });
                    _that.data.checkRadio3g.map((item) => {
                        if (temp.includes(item.value)) {
                            item.checked = true;
                            checkRadioValue3 = item.value;
                        }
                    });
                    _that.data.checkRadio2g.map((item) => {
                        if (temp.includes(item.value)) {
                            item.checked = true;
                            checkRadioValue2 = item.value;
                        }
                    });
                    _that.setData({
                        countryOrArea: res.data.cityOperator.country,
                        operatorName: res.data.cityOperator.operator,
                        src: res.data.cityOperator.operatorpicurl,
                        networkSupportArr: _that.data.networkSupportArr,
                        checkRadio3g: _that.data.checkRadio3g,
                        checkRadio2g: _that.data.checkRadio2g,
                        checkRadio3gValue: checkRadioValue3,
                        checkRadio2gValue: checkRadioValue2,
                        networkSupport: res.data.cityOperator.networksupport,
                        apnArr: JSON.parse(res.data.cityOperator.apnpoint),
                        ussdArr: JSON.parse(res.data.cityOperator.ussd),
                        textareaValue: res.data.cityOperator.backup,
                        pinyinsimple: res.data.cityOperator.pinyinsimple,
                        pinyindetail: res.data.cityOperator.pinyindetail,
                        isApnComplete: true,
                    });
                    if (res.data.cityOperator.lte) {
                        _that.setData({
                            lteNetworkRange:
                                res.data.cityOperator.lte.regionlimit, //区域划分界限
                            ltebasestation:
                                res.data.cityOperator.lte
                                    .basestationdevicemanufacturer, //基站信息
                            ltebasestationid:
                                res.data.cityOperator.lte.basestation,
                            ltecorenet:
                                res.data.cityOperator.lte
                                    .corenetdevicemanufacturer, //核心网信息
                            ltecorenetid: res.data.cityOperator.lte.corenet,
                            lteipmedia:
                                res.data.cityOperator.lte
                                    .ipmediadevicemanufacturer, //ip多媒体系统
                            lteipmediaid: res.data.cityOperator.lte.ipmedia,
                            ltechannelsupport:
                                res.data.cityOperator.lte.channelname, //频段支持
                            ltechannelsupportid:
                                res.data.cityOperator.lte.channelsupport,
                        });
                    }
                    if (res.data.cityOperator.nr) {
                        _that.setData({
                            //NR网络设备商
                            nrNetworkRange:
                                res.data.cityOperator.nr.regionlimit, //区域划分界限
                            nrbasestation:
                                res.data.cityOperator.nr
                                    .basestationdevicemanufacturer, //基站信息
                            nrbasestationid:
                                res.data.cityOperator.nr.basestation,
                            nrcorenet:
                                res.data.cityOperator.nr
                                    .corenetdevicemanufacturer, //核心网信息
                            nrcorenetid: res.data.cityOperator.nr.corenet,
                            nrchannelsupport:
                                res.data.cityOperator.nr.channelname, //频段支持
                            nrchannelsupportid:
                                res.data.cityOperator.nr.channelsupport,
                        });
                    }
                } else {
                    console.log('请求失败');
                }
            },
        });
    },
});
